import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:jd_flutter/base/widget/basic/base_lifecycle_page.dart';
import 'package:jd_flutter/base/widget/basic/base_list_widget.dart';

import '../../net/jd_request.dart';
import '../../utils/loading_util.dart';
import '../pages/empty_page.dart';
import '../refresh/jd_refresh_header.dart';

// 只有下拉 非列表的页面
abstract class TDRequestScrollState<Data, T extends StatefulWidget>
    extends BaseLifecycleState<T> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => false;

  // 缓存数据
  Map? get cacheMap => null;

  /// 是否需要 loading
  bool get needLoading => false;

  // 是否可以自动刷新
  bool get needAutoRefresh => false;

  // 没数据时候 是否显示重试按钮
  bool get showFailEmpty => false;

  bool get customScrollviewControllerNull => false;

  /// 请求服务器的 URL
  @required
  JDApiRequest get apiUrlRequest;

  final ValueNotifier<Map> mapNotifier = ValueNotifier<Map>({});

  final EasyRefreshController _easyRefreshController = EasyRefreshController(
    controlFinishRefresh: true,
  );
  ScrollController scrollController = ScrollController();

  /// 刷新回调
  onRefreshListener() {}

  // 第一次请求是否结束
  bool firstLoadFinish = false;

  @required
  List<Widget> buildContents(BuildContext context, Map map) {
    return [SliverToBoxAdapter(child: Container())];
  }

  Widget? buildTopContent(BuildContext context, Map map) {
    return null;
  }

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () {
      if (cacheMap != null) {
        finishLoadData(cacheMap ?? {});
        mapNotifier.value = cacheMap ?? {};
      }
      if (needLoading) {
        JDLoadingTool.showLoading();
        loadData();
      }
    });
  }

  JDRefreshHeader header = const JDRefreshHeader();
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ValueListenableBuilder<Map>(
        valueListenable: mapNotifier,
        builder: (ctx, value, child) {
          Widget refreshWidget = EasyRefresh(
              controller: _easyRefreshController,
              scrollController: scrollController,
              refreshOnStart: needAutoRefresh,
              header: header,
              onRefresh: () async {
                if (!mounted) {
                  return;
                } else if (_easyRefreshController.headerState?.result ==
                    IndicatorResult.noMore) {
                  endRefresh();
                  return;
                }
                onRefreshListener();
                loadData();
              },
              child: CustomScrollView(
                  controller:
                      customScrollviewControllerNull ? null : scrollController,
                  slivers: needShowSpecialPage(value)
                      ? [getSpecialPage(value)]
                      : [...buildContents(context, value)]));

          Widget? top = buildTopContent(context, value);
          if (top != null) {
            return Column(
              children: [top, Expanded(child: refreshWidget)],
            );
          } else {
            return refreshWidget;
          }
        });
  }

  bool needShowSpecialPage(Map value) {
    if (value.keys.isNotEmpty || mapNotifier.value.keys.isNotEmpty) {
      return false;
    }
    if (!firstLoadFinish) {
      // 显示空白页面
      return true;
    } else if (firstLoadFinish && value.keys.isEmpty) {
      //显示空白提示页 或者网络错误页面
      return true;
    }
    return false;
  }

  Widget getSpecialPage(Map value) {
    if (!firstLoadFinish) {
      return const SliverToBoxAdapter(
        child: BlankPage(),
      );
    } else if (firstLoadFinish && value.keys.isEmpty) {
      return SliverToBoxAdapter(
          child: TDEmptyOrNetworkErrorWidget(
        isNetWorkError: showFailEmpty,
        retryCallBack: () {
          _easyRefreshController.callRefresh();
        },
      ));
    } else {
      return const SliverToBoxAdapter(
        child: BlankPage(),
      );
    }
  }

  Future<Map> loadData() async {
    try {
      Map map = await apiUrlRequest.request;
      firstLoadFinish = true;
      finishLoadData(map);
      endRefresh();
      mapNotifier.value = map;
      JDLoadingTool.dismissLoading();
      return map;
    } catch (e) {
      firstLoadFinish = true;
      endRefresh();
      Map errorMap = {};
      finishLoadData(errorMap);
      mapNotifier.value = errorMap;
      JDLoadingTool.dismissLoading();
      return errorMap;
    }
  }

  finishLoadData(Map map) {}

  dealAfterRequest(Map map) {}

  endRefresh() {
    _easyRefreshController.finishRefresh(IndicatorResult.success);
  }

  // 显示
  @override
  void onResumed() {
    super.onResumed();
    if (isLeaved) {
      isLeaved = false;
      if (!firstLoadFinish || mapNotifier.value.keys.isEmpty) {
        loadData();
      }
    }
  }

  bool isLeaved = false;
  // 离开
  @override
  void onPaused() {
    isLeaved = true;
    IndicatorState? headState = _easyRefreshController.headerState;
    if ((headState?.offset ?? -1) > 0) {
      endRefresh();
      scrollToTop();
    }
    super.onPaused();
  }

  scrollToTop() {
    if (scrollController.positions.isNotEmpty) {
      scrollController.jumpTo(0);
    }
  }

  @override
  dispose() {
    _easyRefreshController.dispose();
    super.dispose();
  }
}
